#!/bin/bash
set -e

# === 配置 ===
FILENAME="mujoco-3.2.7-linux-x86_64.tar.gz"
VERSION="3.2.7"
INSTALL_DIR="$HOME/.mujoco"
TARGET_DIR="$INSTALL_DIR/mujoco-$VERSION"
TMP_DIR="$INSTALL_DIR/tmp_mujoco_extract"
CMAKE_DIR="$TARGET_DIR/lib/cmake/mujoco"

# === 检查压缩包是否存在 ===
if [ ! -f "$FILENAME" ]; then
    echo "❌ 错误：当前目录下没有 $FILENAME，请先放置压缩包"
    exit 1
fi

# === 创建安装目录 ===
mkdir -p "$INSTALL_DIR"

# === 删除旧目录 ===
if [ -d "$TARGET_DIR" ]; then
    echo "👉 目标目录 $TARGET_DIR 已存在，删除旧目录"
    rm -rf "$TARGET_DIR"
fi

# === 临时解压 ===
echo "👉 正在解压到临时目录 $TMP_DIR ..."
rm -rf "$TMP_DIR"
mkdir -p "$TMP_DIR"
tar -zxvf "$FILENAME" -C "$TMP_DIR"

# === 移动解压内容到最终目录 ===
EXTRACTED_DIR=$(find "$TMP_DIR" -maxdepth 1 -mindepth 1 -type d | head -n1)
if [ -z "$EXTRACTED_DIR" ]; then
    echo "❌ 错误：解压失败或压缩包内部目录为空"
    exit 1
fi
mv "$EXTRACTED_DIR" "$TARGET_DIR"
rm -rf "$TMP_DIR"

# === 检查 bin 目录 ===
if [ ! -d "$TARGET_DIR/bin" ] || [ -z "$(ls -A $TARGET_DIR/bin)" ]; then
    echo "❌ 错误：$TARGET_DIR/bin 目录不存在或为空，请检查压缩包"
    exit 1
fi

# === 写入 CMake 配置文件 ===
echo "👉 生成 CMake 配置文件 ..."
mkdir -p "$CMAKE_DIR"

cat > "$CMAKE_DIR/mujocoConfig.cmake" <<EOF
# Auto-generated mujocoConfig.cmake
set(mujoco_INCLUDE_DIR "\${CMAKE_CURRENT_LIST_DIR}/../../../include")
set(mujoco_LIBRARY "\${CMAKE_CURRENT_LIST_DIR}/../../libmujoco.so")

add_library(mujoco::mujoco SHARED IMPORTED)
set_target_properties(mujoco::mujoco PROPERTIES
    IMPORTED_LOCATION "\${mujoco_LIBRARY}"
    INTERFACE_INCLUDE_DIRECTORIES "\${mujoco_INCLUDE_DIR}"
)
EOF

cat > "$CMAKE_DIR/mujocoTargets.cmake" <<EOF
# Dummy mujocoTargets.cmake for compatibility
include("\${CMAKE_CURRENT_LIST_DIR}/mujocoConfig.cmake")
EOF

# === 设置环境变量-没有设置才MUJOCO_HOME才写入 ===
MUJOCO_HOME="$TARGET_DIR"
if ! grep -q "MUJOCO_HOME" ~/.bashrc; then
    echo "👉 写入环境变量到 ~/.bashrc"
    cat <<EOF >> ~/.bashrc

# Mujoco $VERSION
export MUJOCO_HOME=$MUJOCO_HOME
# 然后将MUJOCO_HOME/bin添加到PATH
export PATH=\$MUJOCO_HOME/bin:\$PATH
export LD_LIBRARY_PATH=\$MUJOCO_HOME/lib:\$LD_LIBRARY_PATH

EOF
fi

echo "✅ 安装完成！请执行以下命令让环境变量生效："
echo "   source ~/.bashrc"
echo ""
echo "👉 CMake 已支持 find_package(mujoco REQUIRED)"
echo ""
echo "示例运行："
echo "   \$MUJOCO_HOME/bin/simulate \$MUJOCO_HOME/model/humanoid/humanoid.xml"
echo "   直接运行mujoco：simulate"
